/**
 * 
 */
package com.nari.interfaces.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;

import com.nari.coreframe.dao.hibernate3.GenericDaoImpl;
import com.nari.interfaces.model.IHeatMeterDataBuffer;
import com.nari.platform.date.CalendarUtils;

/**
 * 
 * @author Xiaopeng
 * @date 2013-11-11
 */
public class HeatMeterDataBufferDaoImpl extends GenericDaoImpl<IHeatMeterDataBuffer, String> 
		implements IHeatMeterDataBufferDao {

	/**
	 * 批量保存接口上传的热量表数据
	 * 说明：若存在相同表号、相同抄表日期的的热量表数据，则不保存
	 * @param uploadMissionUID 任务ID
	 * @param meterDataList
	 * @return 返回保存成功的热量表数据个数
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-11-11
	 */
	public int saveMeterDataBatch(String uploadMissionUID, 
			List<IHeatMeterDataBuffer> meterDataList) throws Exception {
		int savedCounter = 0;
		if(meterDataList!=null && meterDataList.size()>0) {
			for(IHeatMeterDataBuffer meterData: meterDataList) {
				int existCounter = this.countMeterDataNumByMark(meterData.getMeterNo(), meterData.getRecordTime());
				//若热量表数据已存在，则不保存
				if(existCounter > 0) {
					continue;
				}
				//保存热量表数据
				meterData.setUploadMissionUID(uploadMissionUID);
				this.saveEntity(meterData);
				savedCounter++;
			}
		}
		return savedCounter;
	}
	
	/**
	 * 通过热量表数据标识(表号、抄表时间)统计热量表数据个数
	 * @param meterNo
	 * @param recordTime
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-11-11
	 */
	public int countMeterDataNumByMark(String meterNo, Date recordTime) throws Exception {
		//上传时间的起始时间
		Date startRecordTime = CalendarUtils.getMinCalBasedSrcCal(CalendarUtils.getInstance(recordTime));
		//上传时间的结束时间
		Date endRecordTime = CalendarUtils.getMaxCalBasedSrcCal(CalendarUtils.getInstance(recordTime));
		String hsql = "select count(*) from IHeatMeterDataBuffer hmdb " +
				"where hmdb.meterNo='"+meterNo+"' " +
				"and hmdb.recordTime between :startTime and :endTime";
		Query query = this.getCurrentSession().createQuery(hsql);
		//设置时间过滤参数
		query.setTimestamp("startTime", startRecordTime).setTimestamp("endTime", endRecordTime);
		return ((Long) query.uniqueResult()).intValue();
	}
	
	/**
	 * 通过任务ID查询接口上传的热量表数据列表
	 * @param uploadMissionUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-11-11
	 */
	public List<IHeatMeterDataBuffer> queryMeterDataListByMissionUID(String uploadMissionUID) 
			throws Exception {
		String hsql = "from IHeatMeterDataBuffer hmdb " +
				"where hmdb.uploadMissionUID='"+uploadMissionUID+"'";
		return this.runQueryHSql(hsql);
	}
	
	/**
	 * 通过任务ID删除接口上传的热量表数据
	 * @param uploadMissionUID
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-11-11
	 */
	public void deleteMeterDataByMissionUID(String uploadMissionUID) throws Exception {
		String hsql = "delete from IHeatMeterDataBuffer hmdb " +
				"where hmdb.uploadMissionUID='"+uploadMissionUID+"'";
		this.runFormatHSql(hsql);
	}
}
